import json

from django.shortcuts import render

# Create your views here.
from django.http import JsonResponse
from django.shortcuts import get_object_or_404
from django.utils import timezone

from .models import Host, City, IDC
from .tool import ping


def city_detail(request, city_id):
    """根据id查找、修改、删除城市信息"""
    city = get_object_or_404(City, pk=city_id)
    # 获取
    if request.method == 'GET':
        return JsonResponse({'id': city.id, 'name': city.name})
    # 修改
    elif request.method == 'PUT':
        data = json.loads(request.body)
        city.name = data['name']
        city.save()
        return JsonResponse({'id': city.id, 'name': city.name})
    # 删除
    elif request.method == 'DELETE':
        city.delete()
        return JsonResponse({'status': 'deleted'}, status=204)


def city_list(request):
    """城市列表"""
    # 获取
    if request.method == 'GET':
        cities = list(City.objects.values())
        return JsonResponse(cities, safe=False)
    # 添加
    elif request.method == 'POST':
        data = json.loads(request.body)
        city = City.objects.create(name=data['name'])
        return JsonResponse({'id': city.id, 'name': city.name}, status=201)


def idc_detail(request, idc_id):
    """机房信息"""
    idc = get_object_or_404(IDC, pk=idc_id)

    if request.method == 'GET':
        # 根据id获取机房信息
        return JsonResponse({
            'id': idc.id,
            'name': idc.name,
            'city': idc.city
        })
    elif request.method == 'PUT':
        # 根据id修改机房信息
        data = json.loads(request.body)
        # 更新名称和所属城市
        idc.name = data['name']
        if 'city_id' in data:
            city = get_object_or_404(City, pk=data['city_id'])
            idc.city = city
        idc.save()
        return JsonResponse({
            'id': idc.id,
            'name': idc.name,
            'city': idc.city
        })
    elif request.method == 'DELETE':
        idc.delete()
        return JsonResponse({'status': 'deleted'}, status=204)


def idc_list(request):
    """机房列表"""
    if request.method == 'GET':
        # 获取
        idcs = list(IDC.objects.values('id', 'name', 'city'))
        return JsonResponse(idcs, safe=False)
    elif request.method == 'POST':
        # 添加
        data = json.loads(request.body)
        # 确保城市存在
        city = get_object_or_404(City, pk=data['city_id'])
        idc = IDC.objects.create(name=data['name'], city=city)
        return JsonResponse({'id': idc.id, 'name': idc.name, 'city_id': city.id}, status=201)


def host_detail(request, host_id):
    """获取单个主机详情"""
    host = get_object_or_404(Host, pk=host_id)
    if request.method == 'GET':
        # 获取
        return JsonResponse({
            'id': host.id,
            'hostname': host.hostname,
            'ip': host.ip,
            'idc': host.idc.name,
            'city': host.idc.city.name
        })
    elif request.method == 'PUT':
        # 更新
        data = json.loads(request.body)
        host.hostname = data['hostname']
        host.ip = data['ip']
        # 如果提供了新密码，则更新
        if 'password' in data:
            host.root_password = data['password']  # 更新加密密码
            host.password_updated_at = timezone.now()  # 更新时间戳
        if 'idc_id' in data:
            idc = get_object_or_404(IDC, pk=data['idc_id'])
            host.idc = idc
        host.save()
        return JsonResponse({
            'id': host.id,
            'hostname': host.hostname,
            'ip': host.ip,
            'idc_id': host.idc_id,
            'password_updated_at': host.password_updated_at.isoformat()
        })


def host_list(request):
    """主机列表"""
    if request.method == 'GET':
        # 获取所有
        hosts = []
        for host in Host.objects.all():
            hosts.append({
                'id': host.id,
                'hostname': host.hostname,
                'ip': host.ip,
                'idc': host.idc.name,
                'city': host.idc.city.name
            })
        return JsonResponse({'hosts': hosts})
    elif request.method == 'POST':
        # 创建
        data = json.loads(request.body)
        idc = get_object_or_404(IDC, pk=data['idc_id'])

        host = Host(
            hostname=data['hostname'],
            ip_address=data['ip_address'],
            idc=idc,
            root_password=data['password']  # 设置加密密码
        )
        host.save()
        return JsonResponse({
            'id': host.id,
            'hostname': host.hostname,
            'ip_address': host.ip,
            'idc': host.idc_id,
            'password_updated_at': host.password_updated_at.isoformat()
        }, status=201)


def host_ping(request, host_id):
    """探测主机是否可达"""
    host = get_object_or_404(Host, pk=host_id)
    response_data = {
        'host_id': host.id,
        'hostname': host.hostname,
        'ip': host.ip,
        'reachable': ping(host.ip)  # 是否ping通
    }

    return JsonResponse(response_data)
